<?php
/**
 * Created by PhpStorm.
 * User: 2016-08-23
 * Date: 2017/9/11
 * Time: 14:27
 */
/**
 * PHP版DES加解密类
 * 可与java的DES(DESede/CBC/PKCS5Padding)加密方式兼容
 *
 */
class CryptDes {
    var $key;
    var $iv;
    function CryptDes($key, $iv){
        $this->key = $key;
        $this->iv = $iv;
    }

    function decrypt($encrypted){
        $key = str_pad($this->key,24,'0');
        $td = mcrypt_module_open(MCRYPT_3DES,'',MCRYPT_MODE_CBC,'');//3DES
        if( $this->iv == '' )
        {
            $iv = @mcrypt_create_iv (mcrypt_enc_get_iv_size($td), MCRYPT_RAND);
        }
        else
        {
            $iv = $this->iv;
        }
        @mcrypt_generic_init($td, $key, $iv);
        $decrypted = mdecrypt_generic($td, $encrypted);
        mcrypt_generic_deinit($td);
        mcrypt_module_close($td);
        $y=$this->pkcs5_unpad($decrypted);
        return $y;
    }
    function pkcs5_unpad($text){
        $pad = ord($text{strlen($text)-1});
        if ($pad > strlen($text)) {
            return false;
        }
        if (strspn($text, chr($pad), strlen($text) - $pad) != $pad){
            return false;
        }
        return substr($text, 0, -1 * $pad);
    }
}
?>